<template>
  <div class="wechat-guide-container" v-loading="loading">
    <div class='wechat-guide-content'>
      <div class='guide-header'>绑定微信公众号，将公众号运营管理托管至平台<br/>聚焦功能一体化，提高转化率</div>
      <ul class='guide-menu'>
        <li class='guide-menu-item'>
          <!-- <div class='item-icon'>
            <span class='iconfont'>&#xe6cb;</span>
          </div> -->
          <div class='item-icon icon1'></div>
          <div class='item-btn-active' @click="goBindWechat()">已有公众号，立即绑定</div>
          <div class='item-tip'>为体验更多功能的使用<br>授权时请把所有权限统一授权给平台<br>若遇到问题，可选择公众号&nbsp;<span @click="addWechats()" class="add-wechats">手动授权</span></div>
        </li>
        <li class='guide-menu-item'>
          <!-- <div class='item-icon'>
            <span class='iconfont'>&#xe6f8;</span>
          </div> -->
          <div class='item-icon icon2'></div>
          <div class='item-btn' @click="goRegisterWechat()">没有公众号，立即申请</div>
          <div class='item-tip'>请在微信公众平台申请新的公众号<br>申请完成后，再到平台进行授权绑定</div>
        </li>
      </ul>
    </div>
    <!-- 添加公众号 -->
    <el-dialog
      append-to-body
      width="600px"
      :title="mechatManage"
      :visible.sync="addDialogFormVisible"
      @close="resetAddSubscription()">
      <el-form
        :model="addSubscription"
        :rules="rulesAdd"
        ref="addSubscriptionRef"
        label-width="120px"
        label-position="left"
        class="demo-ruleForm">
        <div style="display: flex;justify-content: center;margin-bottom: 20px;">
          <div v-if="addSubscription.qrcodeImg" class="wechat-icon" :style="{backgroundImage: 'url(' + getWxImg(addSubscription.qrcodeImg) + ')'}"></div>
          <div v-else class="wechat-icon"></div>
        </div>
        <el-form-item
          label="公众号原始ID"
          prop="wechatUid">
          <el-input
            placeholder="请输入公众号原始ID"
            v-model.trim="addSubscription.wechatUid">
          </el-input>
        </el-form-item>
        <el-form-item
          label="公众号名称"
          prop="wechatName">
          <div style="display: flex">
            <el-input
              placeholder="请输入公众号名称"
              maxlength="32"
              v-model.trim="addSubscription.wechatName">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item
          label="公众号类型"
          prop="wechatType">
          <el-radio-group
            :disabled="mechatManage === '公众号管理'" v-model="addSubscription.wechatType">
            <el-radio label="2">服务号</el-radio>
            <el-radio label="1">订阅号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="公众号AppId"
          prop="appId">
          <div style="display: flex">
            <el-input
              placeholder="请输入公众号AppId"
              v-model.trim="addSubscription.appId">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item
          label="公众号Secret"
          prop="appSecret">
          <el-input
            placeholder="请输入公众号Secret"
            v-model.trim="addSubscription.appSecret">
          </el-input>
        </el-form-item>
        <el-form-item
          label="公众号Token"
          prop="wechatToken">
          <el-input
            placeholder="请输入公众号Token"
            v-model.trim="addSubscription.wechatToken">
          </el-input>
        </el-form-item>
        <el-form-item
          label="公众号AESKey"
          prop="encodingAesKey">
          <el-input
            placeholder="请输入公众号AESKey"
            v-model.trim="addSubscription.encodingAesKey">
          </el-input>
        </el-form-item>
        <el-form-item
          label="公众号主体名称"
          prop="principalName">
          <el-input
            placeholder="请输入公众号认证主体名称"
            v-model.trim="addSubscription.principalName">
          </el-input>
        </el-form-item>
        <div
          v-show="addSubscription.wechatType == 1"
          class='settingBox-header'>
          <span class='iconfont'>&#xe69e;</span> 提示：若想在订阅号中提升功能权限可选择服务号“订阅号+服务号”来提升能力！
        </div>
        <el-form-item
          v-show="addSubscription.wechatType == 1 && serviceList.length"
          label="功能升级号"
          class='article-authority'>
          <el-select
            v-model="addSubscription.expandAppid"
            placeholder="请选择"
            class='actionPermit-select'>
            <el-option v-for='item in serviceList'
              :key='item.appId'
              :label='item.wechatName'
              :value='item.appId'>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="confirmAdd()">确定</el-button>
        <el-button size="small" @click="addDialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {getTanentLimit} from '@/api'
export default {
  name: 'wechatGuide',
  components: {
  },
  data () {
    return {
      loading: false,
      publicTotal: 0, // 当前租户公众号数量
      // limitInfo: {}, // 租户限制信息
      serviceList: [], // 服务号列表
      /* 手动授权相关 */
      addDialogFormVisible: false,
      mechatManage: '添加公众号',
      addSubscription: {
        wechatName: null,
        wechatType: null,
        appId: null,
        appSecret: null,
        encodingAesKey: null,
        wechatToken: null,
        principalName: null,
        wechatUid: null,
        expandAppid: null
      },
      rulesAdd: {
        wechatName: [{required: true, message: '必填', trigger: 'blur'}],
        wechatType: [{required: true, message: '必选', trigger: 'change'}],
        appId: [{ required: true, message: '必填', trigger: 'blur' }],
        appSecret: [{ required: true, message: '必填', trigger: 'blur' }],
        wechatToken: [{ required: true, message: '必填', trigger: 'blur' }],
        encodingAesKey: { max: 43, message: '长度不能超过43个字符', trigger: 'blur' },
        wechatUid: {required: true, message: '必填', trigger: 'blur'}
      }
    }
  },
  methods: {
    // 扫码授权
    goBindWechat () {
      this.loading = true
      let url = `/wechat/server/response/goto_auth_url_show`
      this.get(url).then(res => {
        this.loading = false
        if (res.data.code === 200) {
          window.open(res.data.data.redirectUrl)
          this.$confirm('请在新打开的窗口中完成授权', '提示', {
            confirmButtonText: '授权成功',
            cancelButtonText: '授权失败'
          }).then(() => {
            this.$emit('success')
          }).catch(() => {})
        }
      }).catch(e => {
        this.loading = false
        this.showErrMsg(e.data.message)
      })
    },
    // 手动授权
    addWechats () {
      // if (this.limitInfo.mpCount <= this.publicTotal) {
      //   return this.showErrMsg(`当前公众号授权数量已达到极限(${this.limitInfo.mpCount}个)，可联系客户进行在线升级！`)
      // }
      this.mechatManage = '添加公众号'
      this.addDialogFormVisible = true
      this.fetchServiceList()
    },
    // 添加公众号确定按钮
    confirmAdd () {
      this.$refs.addSubscriptionRef.validate((valid) => {
        if (valid) {
          this.confirmAddWechat()
        } else {
          this.$message({
            message: '请填写必填项',
            type: 'warning'
          })
        }
      })
    },
    // 添加新公众号
    confirmAddWechat () {
      this.loading = true
      let url = `${this.SERVICE_WECHAT}/add`
      let param = {
        wechatName: this.addSubscription.wechatName,
        wechatType: this.addSubscription.wechatType,
        appId: this.addSubscription.appId,
        appSecret: this.addSubscription.appSecret,
        encodingAesKey: this.addSubscription.encodingAesKey,
        wechatToken: this.addSubscription.wechatToken,
        principalName: this.addSubscription.principalName,
        wechatUid: this.addSubscription.wechatUid,
        expandAppid: this.addSubscription.expandAppid
      }
      this.posts(url, param).then(res => {
        this.loading = false
        if (res.data.code === 200) {
          this.$emit('success')
          this.showSucc('添加成功')
          this.addDialogFormVisible = false
        }
      }).catch(e => {
        this.loading = false
        this.addDialogFormVisible = false
        this.handleError(e)
      })
    },
    // 关闭手动授权重置表单
    resetAddSubscription () {
      this.addSubscription = {
        wechatName: null,
        wechatType: null,
        appId: null,
        appSecret: null,
        encodingAesKey: null,
        wechatToken: null
      }
      this.$refs.addSubscriptionRef.resetFields()
    },
    // 申请公众号
    goRegisterWechat () {
      window.open('https://mp.weixin.qq.com/')
    },
    // 获取服务号列表
    fetchServiceList () {
      let url = `${this.SERVICE_WECHAT}/serviceList`
      this.get(url).then(res => {
        let data = res.data.data
        if (data) {
          this.serviceList = data
        } else {
          this.serviceList = []
        }
      }).catch(e => {
        this.handleError(e)
      })
    }
    // // 获取租户限制信息
    // getLimitInfo () {
    //   getTanentLimit({}).then(res => {
    //     if (res.data.code === 200) {
    //       let data = res.data.data
    //       if (data) {
    //         this.limitInfo = res.data.data
    //       } else {
    //         this.limitInfo = {}
    //       }
    //     }
    //   }).catch(err => this.handleError(err))
    // }
  },
  created () {
    // this.getLimitInfo()
  }
}
</script>

<style lang="stylus" scoped>
.wechat-guide-container
  box-sizing border-box
  background #fff
  display flex
  flex-direction column
  height 100%
  position relative
  .wechat-guide-content
    position absolute
    top 0
    bottom 0
    // left 200px
    // right 200px
    left 190px
    right 190px
    display flex
    flex-direction column
    .guide-header
      flex none
      line-height 30px
      font-size 18px
      font-weight 700
      color #000
      text-align center
      padding 20px 0 50px
    .guide-menu
      flex 1
      display flex
      max-height 400px
      .guide-menu-item
        flex 1
        min-width 200px
        display flex
        flex-direction column
        // justify-content center
        align-items center
        border 1px solid #ddd
        border-radius 10px
        padded_box(border-box, 80px 0 0)
        margin-right 54px
        &:last-child
          margin-right 0
        .item-icon
          width 106px
          height 106px
          // width 100px
          // height 100px
          margin-bottom 20px
          &.icon1
            background url('~assets/img/icon-wechat@2x.png') no-repeat center / 100%
          &.icon2
            background url('~assets/img/ic_shengqing@2x.png') no-repeat 0 0 / 100%
        // .item-icon
        //   width 100px
        //   height 100px
        //   margin-bottom 20px
        //   text-align center
        //   line-height 100px
        //   .iconfont
        //     font-size 80px
        //     color #b0d6fd
        .item-btn-active, .item-btn
          width 180px
          height 40px
          line-height 40px
          text-align center
          font-size 14px
          font-weight 400
          border-radius 6px
          cursor pointer
        .item-btn-active
          color #fff
          // background #409eff
          background #4C84FF
        .item-btn
          // color #409eff
          // border 1px solid #409eff
          color #4C84FF
          border 1px solid #4C84FF
        .item-tip
          // line-height 1.7
          // font-size 12px
          // color #999
          line-height 22px
          font-size 14px
          color #888b9c
          text-align center
          margin-top 20px
          .add-wechats
            cursor pointer
            // color #409eff
            color #4c84ff
            cursor pointer
            text-decoration underline
.demo-ruleForm
  >>> .el-input
    width 360px
  .settingBox-header
    width 100%
    margin 0 auto
    line-height 22px
    color #E6A23C
    font-size 12px
    margin-bottom 10px
</style>
